import { create, globSource } from "kubo-rpc-client";
import fs from "fs";
import ini from "ini";
import got from "got";
import appInfo from "./app.js";
import userinfo from "./userinfo.js";

const { identityCardNumber } = userinfo;

Date.prototype.getUTCTime = function () {
    return this.getTime() + this.getTimezoneOffset() * 60 * 1000;
};

Date.prototype.UTCTimeToLocal = function (time) {
    return time - this.getTimezoneOffset() * 60 * 1000;
};

(async () => {
    var gitConfig = ini.parse(fs.readFileSync("./.git/config", "utf-8"));
    console.log(gitConfig['remote "origin"'].url);

    const outputPath = "./dist";

    let ipfs = create({ host: "172.28.237.148", port: "5001", protocol: "http" });
    let { id } = await ipfs.id();
    console.log(id.toString());

    let file;
    for await (file of ipfs.addAll(globSource(outputPath, "**/*", { recursive: true, hidden: true }), { pin: false, wrapWithDirectory: true })) {
    }
    console.log(file.cid.toString());

    let codeHash = file.cid.toString();

    var options = {
        method: "post",
        headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET,POST,OPTIONS" },
        https: { rejectUnauthorized: false },
        responseType: "json",
        timeout: { request: 360 * 1000 },
        json: {},
    };

    try {
        let appGitlab = gitConfig['remote "origin"'].url;
        if (!appInfo.appSdty) return console.log("缺少开发者类型信息！");
        if (appInfo.appSdty === "组织" && !appInfo.appSduu) return console.log("组织开发者缺少组织社会信用代码！");
        options.json = { identityCardNumber, appInfo, appGitlab, codeHash, codeSize: file.size, appPubtime: new Date().getUTCTime() };

        let url = "http://dev.bchain.top:9020/organization/application/type/version/publish";
        // let url = "http://application-unified-resource.bntools.cn:9020/application/type/version/publish";
        let res = await got(url, options);
        if (res.statusCode !== 200) return console.error(res.statusCode, res.statusMessage, res.body);
        if (res.body.statusCode === 0) return console.log("发版成功");
        console.log(res.body);
    } catch (error) {
        console.log(error);
        console.log(error.toString());
    }
})();
